<template>
  <div class="wrapper xc_print">
    <div class="print_wrapper">
      <div class="search_wrapper">
        出版社：<avue-select
          v-model="name"
          placeholder="请选择出版社"
          :dic="dic"
          filterable
          @change="selectName"
        ></avue-select>
        <div class="ml50">
          <el-button type="primary" @click="print">打印</el-button>
        </div>
      </div>
      <!-- <img :src="src"  /> -->
      <div class="print_page" id="printPage">
        <div
          ref="printPage"
          class="printPadding"
          :style="{ width: width + 'px', height: height + 'px' }"
        >
          <div class="title" id="mytitle">
            {{ currentData.publisher }}
          </div>
          <ul>
            <li>
              <span class="flex_between"
                ><span class="spanf">收</span><span class="spanf">货</span
                ><span class="spanf">地</span
                ><span class="spanf">址：</span></span
              >
              <span :style="{ fontSize: size }" class="spanf">
                {{ currentData.address }}
              </span>
            </li>
            <li>
              <span class="flex_between"
                ><span class="spanf">收</span><span class="spanf">货</span
                ><span class="spanf">电</span
                ><span class="spanf">话：</span></span
              >
              <span class="spanf">
                {{ currentData.tel }}
              </span>
            </li>
            <li>
              <span class="flex_between"
                ><span class="spanf">收</span><span class="spanf">货</span
                ><span class="spanf">人：</span></span
              >
              <span class="spanf">
                {{ currentData.name }}
              </span>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="crud_wrapper">
      <avue-crud
        :data="data"
        v-model="form"
        :option="option"
        :table-loading="loading"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        ref="crud"
      ></avue-crud>
    </div>
  </div>
</template>

<script>
import { getData, add, del, update } from "../api/api";
import html2canvas from "html2canvas";
import print from "print-js";
export default {
  mounted() {
    this.onLoad();
    this.width = parseInt(this.mmConversionPx(130)) - 120;
    this.height = parseInt(this.mmConversionPx(65)) - 10;
  },
  data() {
    return {
      name: "",
      loading: true,
      data: [],
      width: "",
      height: "",
      form: {},
      dic: [],
      src: "",
      size: "",
      currentData: {},
      option: {
        dialogWidth: 800,
        viewBtn: true,
        page: false,
        align: "center",
        menuAlign: "center",
        column: [
          {
            label: "出版社",
            prop: "publisher",
            rules: [
              {
                required: true,
                message: "请输入出版社",
                trigger: "blur",
              },
            ],
          },
          {
            label: "姓名",
            prop: "name",
            rules: [
              {
                required: true,
                message: "请输入姓名",
                trigger: "blur",
              },
            ],
          },
          {
            label: "电话号码",
            prop: "tel",
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入电话号码",
                trigger: "blur",
              },
            ],
          },
          {
            label: "地址",
            prop: "address",
            span: 24,
            type: "textarea",
            rules: [
              {
                required: true,
                message: "请输入地址",
                trigger: "blur",
              },
            ],
          },
          {
            label: "备注",
            type: "textarea",
            span: 24,
            prop: "remark",
          },
        ],
      },
    };
  },
  watch: {
    "currentData.address": {
      handler(val, oldVal) {
        let len = val.length;
        if (len > 54) {
          this.size = "14px";
        } else if (len > 72) {
          this.size = "13px";
        }
      },
    },
  },
  methods: {
    selectName(val) {
      this.data.forEach((item) => {
        if (val == item.id) {
          this.currentData = item;
        }
      });
    },
    getDPI() {
      var arrDPI = new Array();
      if (window.screen.deviceXDPI != undefined) {
        arrDPI[0] = window.screen.deviceXDPI;
        arrDPI[1] = window.screen.deviceYDPI;
      } else {
        var tmpNode = document.createElement("DIV");
        tmpNode.style.cssText =
          "width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
        document.body.appendChild(tmpNode);
        arrDPI[0] = parseInt(tmpNode.offsetWidth);
        arrDPI[1] = parseInt(tmpNode.offsetHeight);
        tmpNode.parentNode.removeChild(tmpNode);
      }
      return arrDPI;
    },
    mmConversionPx(value) {
      var inch = value / 25.4;
      var c_value = inch * this.getDPI()[0];
      return c_value;
    },
    DPR() {
      // 获取设备dpi
      if (window.devicePixelRatio && window.devicePixelRatio > 1) {
        return window.devicePixelRatio;
      }
      return 1;
    },
    // print() {
    //     //参考https://blog.csdn.net/weixin_44309374/article/details/106924138
    //   // 获取想要转换的 DOM 节点
    //   const dom = document.querySelector(".printPadding");
    //   // 获取像素比
    //   var scaleBy = this.DPR();
    //   scaleBy = 5;
    //   // 创建自定义 canvas 元素
    //   const canvas = document.createElement("canvas");
    //   // 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
    //   canvas.width = this.width * scaleBy;
    //   canvas.height = this.height * scaleBy;
    //   // 设定 canvas css宽高为 DOM 节点宽高
    // //   canvas.style.width = `${this.width + 10}px`;
    // //   canvas.style.height = `${this.height + 10}px`;
    //   // 获取画笔
    //   const context = canvas.getContext("2d");
    //   // 将所有绘制内容放大像素比倍
    //   // context.scale(scaleBy, scaleBy);
    //   // 将自定义 canvas 作为配置项传入，开始绘制
    //   html2canvas(dom, { canvas, dpi:300,scale: 2.7, background: "#ffffff" }).then(
    //     (imgDom) => {
    //       let url = imgDom.toDataURL();
    //       this.src = url;
    //      // return;
    //       printJS({
    //           maxWidth:this.width,
    //         printable: url,
    //         type: "image",
    //         targetStyle:{
    //             width:this.width+'px',
    //             height:this.height+'px'
    //         },
    //         style: "@page {margin:0mm 0mm}", //去除页眉页脚
    //       });
    //     }
    //   );
    // },
    // print(){

    // }
    //调用打印机
    print() {
      let style = "@page {margin:0mm 0mm}";
      style += `
       @media print {
         .spanf {
                  font-size: 20px !important;
                  color:#000;
                   font-family:"SimHei"
              }
            .wrapper {
            font-size: 15px;
            background-color: #f0f0f0;
            padding: 20px;
            height: 100%;
            }
            .el-card {
            padding: 20px;
            }
            .print_wrapper {
            background-color: white;
            margin-bottom: 20px;
            padding: 20px;
            }
            .print_page {
            margin-top: 30px;
            }
            ul {
            padding: 0;
            margin: 0;
           
            }
            ul li {
            list-style-type: none;
            display: flex;
            font-size: 20px;
            padding: 5px 0;
            }
            .printPadding {
            padding: 5px;
            /* border: 1px solid #bbb; */
            }
            .print_page ul li > span:first-child {
            width: 100px;
            display: inline-block;
            flex-grow: 0;
            }
            .flex_between {
            display: flex !important;
            justify-content: space-between;
            }
            .print_page ul li > span:last-child {
            color: red;
            flex-grow: 0;
            flex: 1;
            padding-left: 5px;
            }
            .ml50 {
            margin-left: 50px;
            display: inline-block;
            }
            .title {
            font-size: 30px !important;
            color:#000;
            margin-bottom: 5px;
            font-weight: bold;
            text-align: center;
             font-family:"SimHei"
            }
        }
          `;

      printJS({
        printable: this.$refs.printPage,
        type: "html",
        style: style, //去除页眉页脚
      });
    },
    // color:black;
     //       font-family:"SimHei"

    // print() {
    //   html2canvas(this.$refs.printPage, {
    //    // scale: 0.85,
    //     dpi: window.devicePixelRatio,
    //     background: "#ffffff", // 一定要添加背景颜色，否则出来的图片，背景全部都是透明的
    //   }).then((canvas) => {
    //     const url = canvas.toDataURL();
    //     this.src = url;
    //     printJS({
    //       printable: url,
    //       type: "image",
    //       style: "@page {margin:0mm 0mm}", //去除页眉页脚
    //     });
    //   });
    // },
    //保存数据
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad();
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },

    //修改数据
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad();
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    // 删除数据
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return del(row.id);
        })
        .then(() => {
          this.onLoad();
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    onLoad(page, params = {}) {
      this.loading = true;
      //Object.assign(params, this.query)

      getData().then((res) => {
        const data = res.data.data;
        this.data = data;
        let dic = [];
        data.forEach((element) => {
          dic.push({ label: element.publisher, value: element.id });
        });
        this.dic = dic;
        this.loading = false;
      });
    },
  },
};
</script>
<style>
.spanf {
  font-size: 20px !important;
}
.wrapper {
  font-size: 15px;
  background-color: #f0f0f0;
  padding: 20px;
  height: 100%;
}
.el-card {
  padding: 20px;
}
.print_wrapper {
  background-color: white;
  margin-bottom: 20px;
  padding: 20px;
}
.print_page {
  margin-top: 30px;
}
ul {
  padding: 0;
  margin: 0;
}
ul li {
  list-style-type: none;
  display: flex;
  font-size: 20px;
  padding: 5px 0;
}
.printPadding {
  padding: 5px;
  /* border: 1px solid #bbb; */
}
.print_page ul li > span:first-child {
  width: 100px;
  display: inline-block;
  flex-grow: 0;
}
.flex_between {
  display: flex !important;
  justify-content: space-between;
}
.print_page ul li > span:last-child {
  color: red;
  flex-grow: 0;
  flex: 1;
  padding-left: 5px;
}
.ml50 {
  margin-left: 50px;
  display: inline-block;
}
.title {
  font-size: 30px !important;
  margin-bottom: 5px;
  font-weight: bold;
  text-align: center;
}
</style>
